package com.ccys.netty.handler;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ccys.common.util.StringUtil;
import com.ccys.netty.config.NettyConfig;
import com.ccys.netty.config.NettyServer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicInteger;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;


   /**
    * @description 描述
    * @date     2024/2/28
    * @author   cloud fly
    */
@Component
@ChannelHandler.Sharable
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
    public static AtomicInteger nConnection = new AtomicInteger();
    @Override
    public void channelRegistered(ChannelHandlerContext ctx)  {
        log.info("========客户端注册=======");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx)  {
        log.info("========客户端注销=======");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx)  {
        log.info("========客户端连接=======");
        nConnection.incrementAndGet();
        log.info("========当前连接数:{}",nConnection.get());

    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx)  {
        log.info("========客户端断开=======");
        nConnection.decrementAndGet();
    }
    /**
     * 一旦连接，第一个被执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerAdded 被调用"+ctx.channel().id().asLongText());
        // 添加到channelGroup 通道组
        NettyConfig.getChannelGroup().add(ctx.channel());
    }



    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
        ByteBuf content = fullHttpRequest.content();
        ByteBuf byteBuf = content.readerIndex(0);
        //byteBuf.toString(CharsetUtil.UTF_8);
        String msg = byteBuf.toString(CharsetUtil.UTF_8);//CharsetUtil.UTF_8
        // 读取消息内容到字节数组
        byte[] bytes = new byte[content.readableBytes()];
        content.readBytes(bytes);

        // 将字节数组按照 UTF-8 编码转换为字符串
       msg = new String(bytes, Charset.forName("UTF-8"));
        log.info("服务器收到消息：{}",msg);
        // 继续处理 HTTP 请求逻辑
        if (fullHttpRequest.uri().equals("/your-api-endpoint")) {
            // 处理特定接口请求逻辑
            String responseContent = "Hello, this is the response from the server";
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(responseContent.getBytes()));
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
            ctx.writeAndFlush(response);
        } else {
            // 处理其他请求
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND);
            ctx.writeAndFlush(response);
        }
        if(StringUtil.isNotEmpty(msg)) {
            // 获取用户ID
            JSONObject jsonObject = JSONUtil.parseObj(msg);
            String userId = jsonObject.getStr("userId");

            // 将用户ID作为自定义属性加入到channel中，方便随时channel中获取用户ID
            AttributeKey<String> key = AttributeKey.valueOf("userId");
            ctx.channel().attr(key).setIfAbsent(userId);

            // 关联channel
            NettyConfig.getUserChannelMap().put(userId,ctx);

            // 回复消息
            ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器连接成功！"));
        }

    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerRemoved 被调用"+ctx.channel().id().asLongText());
        // 删除通道
        NettyConfig.getChannelGroup().remove(ctx.channel());
        removeUserId(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("异常：{}",cause.getMessage());
        // 删除通道
        NettyConfig.getChannelGroup().remove(ctx.channel());
        removeUserId(ctx);
        ctx.close();
    }

    /**
     * 删除用户与channel的对应关系
     * @param ctx
     */
    private void removeUserId(ChannelHandlerContext ctx){
        AttributeKey<String> key = AttributeKey.valueOf("userId");
        String userId = ctx.channel().attr(key).get();
        if(StringUtil.isNotEmpty(userId)) {
            NettyConfig.getUserChannelMap().remove(userId);
        }

    }
}
